package com.bright.ghj.overt.web.controller;

import com.bright.ghj.common.pojo.bo.RestResult;
import com.bright.ghj.common.util.DateUtil;
import com.bright.ghj.common.util.StringUtil;
import com.bright.ghj.overt.enums.DataStatus;
import com.bright.ghj.overt.manager.OpenReportRecordManager;
import com.bright.ghj.overt.pojo.dto.OpenReportRecordDTO;
import com.bright.ghj.common.util.excel.ExcelUtil;
import com.bright.ghj.common.util.FileUtil;
import com.bright.ghj.overt.util.DockingUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author hxj
 * @Date 2024/1/10 20:49
 * @Description
 */
@RequestMapping("/test")
@RestController
@RequiredArgsConstructor
public class TestController {


    private final OpenReportRecordManager openReportRecordManager;

//    private final BaseDataService baseDataService;
//    private final NavigateService navigateService;
//    private final MQProduceService mqProduceService;

    private final RestTemplate restTemplate;

//    @GetMapping("/moveDataStatus/{id}/{status}")
//    public RestResult moveDataStatus(@PathVariable String id, @PathVariable String status) {
////        operateService.moveDataStatus(Integer.parseInt(id), Integer.parseInt(status));
//        OpenReportRecordDTO openReportRecordDTO = openReportRecordManager.getById(Integer.parseInt(id));
//        String instanceId = openReportRecordDTO.getFlowId();
//        String newStepName = DataStatus.getByStatus(Integer.parseInt(status)).getDefinitionKey();
//
////        flowManager.moveToStepByStepNameByInstanceId(instanceId, newStepName);
//        return RestResult.success();
//    }

//    @GetMapping("/migrate/{from}/{to}")
//    public RestResult migrate(@PathVariable String from, @PathVariable String to) {
////        flowManager.procInstMigration(from, to);
//        return RestResult.success();
//    }

//    @GetMapping("/excel/export")
//    public void excelExport(HttpServletResponse response) {
//
////        List<List<String>> headList = new ArrayList<>();
////        for (String strings : Arrays.asList("序号", "列1", "列2", "列3")) {
////            ArrayList<String> list = new ArrayList<>(1);
////            list.add(strings);
////            headList.add(list);
////        }
////        List<List<String>> dataList = new ArrayList<>();
////        dataList.add(Arrays.asList("1", "aaaa", "45.00", "2024-01-11"));
////        dataList.add(Arrays.asList("2", "bbbb", "90.00", "2024-01-11"));
////        dataList.add(Arrays.asList("3", "cccc", "145.00", "2024-01-11"));
////        try {
////            ExcelUtil.exportExcel(response, "test", "工作表1", headList, dataList);
////        } catch (IOException e) {
////            throw new RuntimeException(e);
////        }
//
//        String jsonString = "[{\"c1\":\"负债\",\"c2\":1,\"c3\":100,\"c4\":200},{\"c1\":\"收益\",\"c2\":2,\"c3\":300.5,\"c4\":420.23}]";
//        ObjectMapper objectMapper = new ObjectMapper();
//        List<Map<String, Object>> listData;
//        try {
//            listData = objectMapper.readValue(jsonString, List.class);
//        } catch (JsonProcessingException e) {
//            throw new RuntimeException(e);
//        }
//
//        Map<String, Object> otherParamData = new HashMap<>();
//        otherParamData.put("tbdw", "石东联社");
//        otherParamData.put("footer1", "罗辑");
//        otherParamData.put("footer2", "叶文洁");
//        otherParamData.put("footer3", "吴悦");
//        otherParamData.put("footer4", "庄严");
//
//        response.setCharacterEncoding("utf-8");
//        try {
//            // 导出的excel文件名
//            String exportExcelFileName = "测试按模板导出.xlsx";
//            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(exportExcelFileName, "utf-8"));
//        } catch (UnsupportedEncodingException e) {
//            throw new RuntimeException(e);
//        }
//        response.setContentType("application/vnd.ms-excel;charset=gb2312");
//        try {
//            ExcelUtil.writeExcelToWebByTemplate(response.getOutputStream(), "D:\\hxj\\test\\cwgk\\test.xlsx", listData, otherParamData);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//
//
//    }

//    @GetMapping("/excel/export/noTemplate")
//    public void excelExportNoTemplate(HttpServletResponse response) {
//
//        String jsonString = "[{\"c1\":\"负债\",\"c2\":1,\"c3\":100,\"c4\":200},{\"c1\":\"收益\",\"c2\":2,\"c3\":300.5,\"c4\":420.23}]";
//        ObjectMapper objectMapper = new ObjectMapper();
//        List<Map<String, Object>> listData;
//        try {
//            listData = objectMapper.readValue(jsonString, List.class);
//        } catch (JsonProcessingException e) {
//            throw new RuntimeException(e);
//        }
//        response.setCharacterEncoding("utf-8");
//        try {
//            // 导出的excel文件名
//            String exportExcelFileName = "测试按模板导出.xlsx";
//            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(exportExcelFileName, "utf-8"));
//        } catch (UnsupportedEncodingException e) {
//            throw new RuntimeException(e);
//        }
//        response.setContentType("application/vnd.ms-excel;charset=gb2312");
//        try {
//            ExcelUtil.writeExcelToWebByTemplate(response.getOutputStream(), "D:\\hxj\\test\\cwgk\\test.xlsx", listData, otherParamData);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//
//
//    }

//    @GetMapping("/excel/import")
//    public RestResult excelImport() {
//        List<Map<String, Object>> maps;
//        try {
//            maps = ExcelUtil.readExcelFromFile(new File("D:\\hxj\\test\\cwgk\\template1.xlsx"), null);
//        } catch (IOException e) {
//            return RestResult.fail(e.getMessage());
//        }
//        return RestResult.success(maps);
//    }

//    @GetMapping("/access")
//    public RestResult testAccess() throws SQLException {
//        List<Map<String, Object>> maps = null;
////        Connection conToAccess = AccessDBUtil.initConnection(new File("E:\\hxj_E\\test\\新雅街202306至202306.bj"), "",
////                "");
////        if (conToAccess == null) {
////            System.out.println("连接未成功");
////        } else {
////            Statement fromSm = conToAccess.createStatement();
//////		String updateSql = "alter table [Rep_11] add months int; update [Rep_11] set months=6 where years=2023";
//////		try {
//////			ConnectUtil.openSql(fromSm, "alter table [Rep_11] add months int");
//////			ConnectUtil.openSql(fromSm, "update [Rep_11] set months=6 where years=2023");
//////		} catch (Throwable e1) {
//////			e1.printStackTrace();
//////		}
////            String sql = "select count(*) from [Rep_11] where zth in ( select zth from zt where ztparent like '00%') and (years*100+months)>=202306 and (years*100+months)<=202306";
//////		String sql = "select top 5 * from [Rep_11] where years=2023";
////            List<List<Object>> fromList = AccessDBUtil.getList(fromSm, sql);
////            System.out.println(fromList);
////            System.out.println("测试完成！");
////
////            conToAccess.close();
////        }
//
//
//
////        ImportAccessCommand importAccessDTO = new ImportAccessCommand();
////        // 是否选定只导入某些表 没指定则全部导入
////        if (importAccessDTO.getTableNames() == null || importAccessDTO.getTableNames().length == 0) {
////            String[] tableNames = ListUtil.toSingleList(navigateService.listTableTypesByMenuId(DataConstant.CW_CATEGORY), TableTypeVO::getTableName).toArray(new String[0]);
////            System.out.println(Arrays.asList(tableNames));
////            importAccessDTO.setTableNames(tableNames);
////        }
//////        importAccessDTO.setTableNames(new String[] {"rep_01", "rep_02"});
//        File file = new File("E:\\hxj_E\\test\\新雅街202306至202306.bj");
////        try {
////            baseDataService.importAccess(importAccessDTO, file);
////        } catch (Exception e) {
////            throw new RuntimeException(e);
////        }
////        MqMessage mqMessage = new MqMessage();
////        mqMessage.setTopicType(RocketConstant.TOPIC_ACCESS_IMPORT);
////        mqMessage.setKeyword(UUID.randomUUID().toString());
////        mqMessage.setReadFlag(false);
////        mqMessage.setFile(file);
////        mqProduceService.sendMessage(mqMessage);
//
//        return RestResult.success(maps);
//    }
//
//    @PostMapping("/testFileType")
//    public RestResult testFileType(MultipartFile file) throws Exception {
//        String fileType = FileUtil.getFileTypeByInputStream(file.getInputStream(), file.getOriginalFilename());
//        return RestResult.success(fileType);
//    }

//    @PostMapping("/testRestTemplate")
//    public RestResult testRestTemplate(MultipartFile file) throws IOException {
//        //设置请求头，请求类型为json
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
//
//        byte[] fileData;
//
//        if (file == null) {
//
//            fileData = FileUtil.getFileBytesFromURL("http://hz3z.cwgk.net:8899/tdlz_ht/uploads/new/20240112/202401121519430497_209_change_280x160.jpg");
//            if (fileData == null) {
//                throw new RuntimeException("fileData获取失败");
//            }
//
//        } else {
//            fileData = file.getBytes();
//        }
//        ByteArrayResource fileAsResource = new ByteArrayResource(fileData) {
//            @Override
//            public String getFilename() {
//                return file == null ? "test.jpg" : file.getOriginalFilename();
//            }
//
//            @Override
//            public long contentLength() {
//                return fileData.length;
//            }
//        };
//        MultiValueMap<String, Object> dataParam = new LinkedMultiValueMap<>();
//        dataParam.add("file", fileAsResource);
//        dataParam.add("fileName", file == null ? "test.jpg" : file.getOriginalFilename());
//
//        //用HttpEntity封装整个请求报文
//        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(dataParam, headers);
////        restTemplate.postForObject("https://3z.by.gov.cn/store/xx", request, Map.class, dataParam);
//        ResponseEntity<Map> exchange = restTemplate.exchange("https://3z.by.gov.cn/store/file", HttpMethod.POST, request, Map.class);
//        return RestResult.success(exchange);
//    }
//
//    @GetMapping("/testContext")
//    public RestResult testContext(HttpServletRequest httpServletRequest) throws Exception {
//        String realPath = httpServletRequest.getSession().getServletContext().getRealPath("/");
//        return RestResult.success(realPath);
//    }

    @GetMapping("/docking")
    public RestResult testDocking(Integer years, Integer months, String tableName, String zth) throws Exception {
        String timestamp = DateUtil.getNowString();
        String nonce = RandomStringUtils.randomAlphanumeric(16);
        String sign = URLEncoder.encode(DockingUtil.getSign("apipysw4eHE3RBAb", nonce, timestamp), "UTF-8");

        String url = "http://localhost:9991/getPublicData?years=" + years + "&months=" + months + "&tableName=" + tableName + "&zth=" + zth
                + "&appKey=2025050816572200000&nonce=" + nonce + "&timestamp=" + URLEncoder.encode(timestamp, "UTF-8") + "&sign=" + sign;
        return RestResult.success(url);
//        ResponseEntity<Object> forEntity = restTemplate.getForEntity(url, Object.class);
//        return RestResult.success(forEntity.getBody());
//        return RestResult.success();
    }

    @GetMapping("/docking/getPublicData")
    public String testDockingCheckSign(String nonce, String timestamp, String sign) throws Exception {
        String realSignValue = DockingUtil.getSign("apipysw4eHE3RBAb", nonce, timestamp);
        boolean isValid = StringUtil.equals(realSignValue, URLDecoder.decode(sign, "UTF-8"));
        System.out.printf("是否合法：%s， 合法签名：%s，传入签名：%s%n", isValid, realSignValue, URLDecoder.decode(sign, "UTF-8"));
        return isValid ? "合法" : "不合法！";
    }

}
